package com.misty.blog.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.misty.blog.service.TagService;
import com.misty.common.bean.Result;
import com.misty.common.constants.ResultEnum;
import com.misty.dao.domain.BlogTag;
import com.misty.dao.domain.Tag;
import com.misty.dao.domain.Users;
import com.misty.dao.mapper.BlogTagMapper;
import com.misty.dao.mapper.TagMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cthulhu
 * @since 2022-11-21
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Resource
    private TagMapper tagMapper;

    @Resource
    private BlogTagMapper blogTagMapper;

    /**
     *
     * @Param
     * @return
     * @Description 获取博客对应标签
     * @Date
     **/
    @Override
    public Result<List<String>> selectTagNameByBlog(Integer blogId) {
        QueryWrapper<BlogTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("blog_tag.blog_id",blogId);
        List<Tag> tags = tagMapper.selectTagNameByBlog(queryWrapper);
        if(CollUtil.isEmpty(tags)){
            return Result.error("获取博客对应标签失败！");
        }
        List<String> collect = tags.stream()
                .map((tag) -> tag.getName())
                .collect(Collectors.toList());
        return Result.success("获取博客对应标签成功！",collect);
    }

    /**
     *
     * @Param
     * @return
     * @Description 获取用户对应博客标签
     * @Date
     **/
    @Override
    public Result<List<String>> selectTagNameByUser(Integer userId) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("users.id",userId);
        List<Tag> tags = tagMapper.selectTagNameByUser(queryWrapper);
        if(CollUtil.isEmpty(tags)){
            return Result.error("获取用户对应博客标签失败！");
        }
        List<String> collect = tags.stream()
                .map((tag) -> tag.getName())
                .collect(Collectors.toList());
        return Result.success("获取用户对应博客标签成功！",collect);
    }

    /**
     *
     * @Param
     * @return
     * @Description 获取所有标签
     * @Date
     **/
    @Override
    public Result<List<String>> getAllTag() {
        List<Tag> tagList = tagMapper.selectList(null);
        if(CollUtil.isEmpty(tagList)){
            Result.error("获取所有标签列表失败!");
        }
        List<String> collect = tagList.stream()
                .distinct()
                .map((tag) -> tag.getName())
                .collect(Collectors.toList());
        return Result.success("获取所有标签列表成功!",collect);

    }



    /**
     *
     * @Param
     * @return
     * @Description 批量添加标签
     * @Date
     **/
    @Override
    @Transactional(transactionManager = "mistyTransactionManager")
    public Result<?> addAllTag(List<String> tagList, Integer blogId) {
        for (String tag : tagList) {
            //获取所有tag列表
            Result<List<String>> allTag = this.getAllTag();
            List<String> data = allTag.getData();

            Tag insertTag = new Tag();
            insertTag.setName(tag);

            //没有这样的tag，则新增
            if(!data.contains(tag)){
                int insert = tagMapper.insert(insertTag);
                if(insert <= 0){
                    return Result.error("批量添加标签失败!");
                }

            }else {
//                有则查询tagId
                QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
                tagQueryWrapper.lambda().eq(Tag::getName,tag);
                Tag tmpTag = tagMapper.selectOne(tagQueryWrapper);
                if(tmpTag == null){
                    return Result.error("批量添加标签失败!");
                }
                insertTag.setId(tmpTag.getId());
            }

            //插入blog_tag中间表
           BlogTag blogTag = new BlogTag();
            blogTag.setBlogId(blogId)
                    .setTagId(insertTag.getId());
            int insert1 = blogTagMapper.insert(blogTag);
            if(insert1 <= 0){
                return Result.error("批量添加标签失败!");
            }
        }

        return Result.success("批量添加标签成功!");
    }

    /**
     *
     * @Param
     * @return
     * @Description 批量删除标签
     * @Date
     **/
    @Override
    @Transactional(transactionManager = "mistyTransactionManager")
    public Result<?> removeAllTag(List<String> tagList, Integer blogId) {
        //获取所有tag
        List<Tag> allTag = tagMapper.selectList(null);
        if(CollUtil.isEmpty(allTag)){
            Result.error("获取所有标签列表失败!");
        }

        for (String tag : tagList) {

            //获取对应tagId
            List<Integer> integerList = allTag.stream()
                    .filter((tag1) -> tag.equals(tag1.getName()))
                    .map(tag1 -> tag1.getId())
                    .collect(Collectors.toList());

            //blog_tag中间表
            UpdateWrapper<BlogTag> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(BlogTag::getBlogId,blogId)
                    .eq(BlogTag::getTagId,integerList.get(0));
            int delete = blogTagMapper.delete(updateWrapper);
            if(delete <= 0){
                return Result.error("批量删除标签失败!");
            }
        }

        return Result.success("批量删除标签成功!");
    }

}
